<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "ProductView",

  inject: ['reload'],

  data() {
    return {
      // 产品搜索表单对象
      productQuery: {
        name: '',
        guidePriceS: '',
        guidePriceE: '',
        state: ''
      },
      // 产品列表对象
      productList: [],
      // 每页显示多少条数据
      pageSize: 0,
      // 总共查询多少数据
      total: 0,
      // 产品负责人下拉列表
      ownerOptions: [{}],
      // 产品搜索表单验证规则
      productRules: {
        name: [
          {required: true, message: '产品名称不能为空', trigger: 'blur'}
        ],
        guidePriceS: [
          {required: true, message: '起始价格不能为空', trigger: 'blur'},
          {pattern: /^-?(0|([1-9][0-9]*))(\.[\d]{1,2})?$/, message: "起始价格必须是整数或两位小数", trigger: "blur"}
        ],
        guidePriceE: [
          {required: true, message: '最高价格不能为空', trigger: 'blur'},
          {pattern: /^-?(0|([1-9][0-9]*))(\.[\d]{1,2})?$/, message: "最高价格必须是整数或两位小数", trigger: "blur"}
        ],
        quotation: [
          {required: true, message: '经销商报价不能为空', trigger: 'blur'},
          {pattern: /^-?(0|([1-9][0-9]*))(\.[\d]{1,2})?$/, message: "报价必须是整数或两位小数", trigger: "blur"}
        ],
        state: [
          {required: true, message: '请选择产品状态', trigger: 'change'}
        ]
      },
      // 选择的产品id数组
      productIdArray: [],
      // 编辑弹窗相关数据
      productDialogVisible: false,
      productEditQuery: {
        id: null,
        name: '',
        guidePriceS: '',
        guidePriceE: '',
        quotation: '',
        state: null
      },
      // 其他数据...
      dialogTitle: '编辑产品',  // 用来动态修改弹窗标题
    }
  },

  methods: {
    // 查询产品列表数据
    getData(current) {
      doGet("/api/products", {
        current: current,
        name: this.productQuery.name,
        guidePriceS: this.productQuery.guidePriceS,
        guidePriceE: this.productQuery.guidePriceE,
        state: this.productQuery.state,
      }).then(resp => {
        if (resp.data.code === 200) {
          this.productList = resp.data.data.list;
          this.total = resp.data.data.total;
          this.pageSize = resp.data.data.pageSize;
        }
      });
    },

    // 分页函数
    toPage(current) {
      this.getData(current);
    },

    // 搜索
    onSearch() {
      this.getData(1);
    },

    // 重置搜索条件
    onReset() {
      this.productQuery = {};
      this.onSearch();
    },

    // 添加新产品
    add() {
      this.productDialogVisible = true;
      this.productEditQuery = {}; // 清空表单
      this.dialogTitle = '添加产品';  // 动态设置标题
    },

    // 编辑产品
    edit(id) {
      doGet("/api/product/" + id).then(resp => {
        if (resp.data.code === 200) {
          this.productEditQuery = resp.data.data;
          this.productDialogVisible = true;
          this.dialogTitle = '编辑产品';  // 动态设置标题
        }
      });
    },

    // 提交编辑的产品数据
    saveProductEdit() {
      this.$refs.productEditForm.validate((isVaild) => {
        if (isVaild) {
          // 如果 id 存在，调用编辑接口
          if (this.productEditQuery.id) {
            doPut("/api/product/edit", this.productEditQuery).then(resp => {
              if (resp.data.code === 200) {
                messageTip("修改成功", "success");
                this.productDialogVisible = false;
                this.getData(1); // 重新加载数据
                this.reload();
              } else {
                messageTip("修改失败", "error");
              }
            });
          } else {
            // 如果 id 不存在，调用添加接口
            doPost("/api/product/add", this.productEditQuery).then(resp => {
              if (resp.data.code === 200) {
                messageTip("添加成功", "success");
                this.productDialogVisible = false;
                this.getData(1); // 重新加载数据
                this.reload();
              } else {
                messageTip("添加失败", "error");
              }
            });
          }
        }
      })
    },

    // 删除产品
    del(id) {
      messageConfirm("确定要删除该产品吗?").then(() => {
        doDelete("/api/product/" + id, {}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("删除产品成功", "success");
            this.getData(1); // 重新加载数据
            this.reload();
          } else {
            messageTip("删除产品失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消删除产品", "warning");
      });
    },

    // 批量删除
    batchDel() {
      if (this.productIdArray.length <= 0) {
        messageTip("请选择要删除的产品", "warning");
        return;
      }
      messageConfirm("确定要删除这些产品吗?").then(() => {
        let ids = this.productIdArray.join(",");
        doDelete("/api/product", {ids: ids}).then(resp => {
          if (resp.data.code === 200) {
            messageTip("批量删除成功", "success");
            this.getData(1); // 重新加载数据
            this.reload();
          } else {
            messageTip("批量删除失败，原因：" + resp.data.msg, "error");
          }
        });
      }).catch(() => {
        messageTip("取消批量删除产品", "warning");
      });
    },

    // 处理表格选择
    handleSelectionChange(selectionDataArray) {
      this.productIdArray = selectionDataArray.map(item => item.id);
    }
  },

  mounted() {
    this.getData(1);
  }
};
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="productQuery" :rules="productRules" style="margin-bottom: 20px;">
      <el-form-item label="产品名称">
        <el-input v-model="productQuery.name" placeholder="请输入产品名称" clearable/>
      </el-form-item>
      <el-form-item label="起始价格">
        <el-input v-model="productQuery.guidePriceS" placeholder="请输入起始价格" clearable/>
      </el-form-item>
      <el-form-item label="最高价格">
        <el-input v-model="productQuery.guidePriceE" placeholder="请输入最高价格" clearable/>
      </el-form-item>
      <el-form-item label="状态" style="width: 200px">
        <el-select v-model="productQuery.state" placeholder="请选择状态" clearable>
          <el-option label="在售" :value="0"/>
          <el-option label="售罄" :value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜 索</el-button>
        <el-button type="primary" plain @click="onReset">重 置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-button type="primary" @click="add()">添加产品</el-button>
    <el-button type="danger" @click="batchDel()">批量删除</el-button>

    <!-- 数据展示表格 -->
    <el-table :data="productList" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column property="name" label="产品名称"/>
      <el-table-column property="guidePriceS" label="起始价格"/>
      <el-table-column property="guidePriceE" label="最高价格"/>
      <el-table-column property="quotation" label="经销商报价"/>
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.state === 0 ? 'success' : 'danger'" disable-transitions>
            {{ scope.row.state === 0 ? '在售' : '售罄' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间"/>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="edit(scope.row.id)">编辑</el-button>
          <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize" @current-change="toPage"/>

    <!--编辑弹窗-->
    <el-dialog v-model="productDialogVisible" :title="dialogTitle" width="55%" center draggable>
      <el-form ref="productEditForm" :model="productEditQuery" label-width="110px" :rules="productRules">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productEditQuery.name" placeholder="请输入产品名称" clearable/>
        </el-form-item>
        <el-form-item label="起始价格" prop="guidePriceS">
          <el-input v-model="productEditQuery.guidePriceS" placeholder="请输入起始价格" clearable/>
        </el-form-item>
        <el-form-item label="最高价格" prop="guidePriceE">
          <el-input v-model="productEditQuery.guidePriceE" placeholder="请输入最高价格" clearable/>
        </el-form-item>
        <el-form-item label="经销商报价" prop="quotation">
          <el-input v-model="productEditQuery.quotation" placeholder="请输入报价" clearable/>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="productEditQuery.state" placeholder="请选择状态" clearable>
            <el-option label="在售" :value="0"/>
            <el-option label="售罄" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProductEdit()">保存</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.el-pagination {
  margin-top: 12px;
}
</style>
